<!--最初版本备份  -->
<template>
  <jke-modal
    :visible.sync="jkeForm.visible"
    :width="1200"
    :title="jkeForm.title"
    :fullscreen.sync="jkeForm.fullscreen"
    :switchFullscreen="jkeForm.switchFullscreen"
  >
    <!--  -->
    <crumbs
      @goBack="goBack"
      :superiorMenu="['销售管理', '销售合同']"
      marginBottom="10px"
      :currentMenu="jkeForm.title"
    ></crumbs>
    <div class="form-body">
      <a-card title="基本信息" :bordered="false">
        <a-form :form="form" @submit="submitProcess" layout="vertical">
          <a-form-item label="订单编号">
            <a-input
              v-decorator="[
                'contractCode',
                {
                  rules: [
                    {
                      required: true,
                      message: '请输入订单编号或自动生成',
                    },
                    {
                      message: '该值不可用，系统中已存在！',
                      validator: (rule, value, callback) =>
                        validateDuplicateValue('erp_sale_contract', 'contract_code', value, queryId, callback),
                    },
                  ],
                },
              ]"
              placeholder="不输入则自动生成"
            />
            <span class="btn-text code-btn" @click="genEntityCode">自动生成</span>
          </a-form-item>
          <!-- <a-form-item label="合同名称" prop="contractName">
            <a-input
              :maxLength="30"
              v-decorator="[
                'contractName',
                {
                  rules: [{ required: true, message: '请输入合同名称' }],
                },
              ]"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="签订人" prop="signUserCode">
            <j-select-user-by-dep
              :value="signUser"
              v-decorator="['signUserCode', { rules: [{ required: true, message: '请选择签订人' }] }]"
              @changeRow="userFilter"
              :seldep="true"
              :modalWidth="1000"
              :multi="false"
            ></j-select-user-by-dep>
          </a-form-item> -->
          <a-form-item label="客户" prop="customerId">
            <a-select
              placeholder="请选择"
              allowClear
              showSearch
              :filter-option="filterOption"
              @select="selectCustom"
              @change="selectChange"
              v-decorator="['customerId', { rules: [{ required: true, message: '请选择客户' }] }]"
            >
              <a-select-option v-for="option in customSelectList" :key="option.id" :value="option.id">{{
                option.belongUserIdText
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item></a-form-item>
          <!-- <a-form-item label="合同金额" prop="amount">
            <a-input
              :disabled="isEdit"
              v-decorator="[
                'amount',
                { rules: [{ required: true, message: '请输入合同金额' }, { validator: validateToPrice }] },
              ]"
              @input="(e) => inputPrice(e)"
              placeholder="请输入"
            />
          </a-form-item>
          <a-form-item label="承诺交期">
            <a-date-picker
              v-decorator="['promiseDate', { rules: [{ required: true, message: '请选择承诺交期' }] }]"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item label="合同起始日期">
            <a-date-picker
              v-decorator="['contractStartDate', { rules: [{ required: true, message: '请选择合同起始日期' }] }]"
              style="width: 100%"
              @change="(e) => (startValue = e)"
              :disabled-date="disabledStartDate"
            />
          </a-form-item>
          <a-form-item label="合同终止日期">
            <a-date-picker
              v-decorator="['contractEndDate', { rules: [{ required: true, message: '请选择合同终止日期' }] }]"
              style="width: 100%"
              @change="(e) => (endValue = e)"
              :disabled-date="disabledEndDate"
            />
          </a-form-item>
          <a-form-item label="签订日期">
            <a-date-picker
              v-decorator="['signDate', { rules: [{ required: true, message: '请选择签订日期' }] }]"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item label="合同原件" style="width: 100%; margin-bottom: 0">
            <file-upload :ids="attachment" @getFileList="getFileList"></file-upload>
            <p style="line-height: 30px; color: #8d8d8d">最多上传5个文件，每个大小不可超过20M</p>
          </a-form-item> -->
        </a-form>
      </a-card>
      <a-card title="自定义信息" :bordered="false">
        <a-form :form="form" @submit="submitProcess" layout="vertical">
          <a-form-item label="下拉选择" prop="customerId">
            <a-select
              placeholder="请选择"
              allowClear
              showSearch
              :filter-option="filterOption"
              @select="selectCustom"
              @change="selectChange"
              v-decorator="['customerId', { rules: [{ required: true, message: '请选择客户' }] }]"
            >
              <a-select-option v-for="option in customSelectList" :key="option.id" :value="option.id">{{
                option.belongUserIdText
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="输入框" prop="amount">
            <a-input @input="(e) => inputPrice(e)" placeholder="请输入" />
          </a-form-item>
          <a-form-item label="时间" prop="time">
            <a-date-picker style="width: 100%"></a-date-picker>
          </a-form-item>
        </a-form>
      </a-card>
      <a-card title="商品明细" :bordered="false" style="margin: 12px 0 24px">
        <j-editable-table
          ref="goodsTable"
          :loading="goodsTable.loading"
          :columns="goodsTable.columns"
          :dataSource="goodsTable.dataSource"
          :maxHeight="300"
          :rowNumber="true"
          :actionButton="true"
          :addActionButton="false"
          :rowSelection="true"
          :delActionBtn="false"
          @valueChange="valueChange"
        >
          <template #options>
            <a-button type="primary" icon="plus" @click="selectMulti" style="margin-right: 10px">添加</a-button>
            <a-button type="primary" icon="minus" @click="selectMulti" style="margin-right: 10px">删除</a-button>
            <PubImport
              ref="PubImport"
              tableCode="MESS_PRODUCT_FLOW"
              modelName="物品明细导入模板"
              style="margin-right: 10px"
            />
            <!-- <a-button type="Default" @click="selectMulti" style="margin-right: 10px">设置列</a-button> -->
          </template>
          <template v-slot:action="props">
            <a-popconfirm
              :disabled="disabledShip(props)"
              title="是否删除?"
              ok-text="是"
              cancel-text="否"
              @confirm="handleDeleteGood(props)"
            >
              <span :class="disabledShip(props) ? 'del-text-disabled' : 'del-text'">删除</span>
            </a-popconfirm>
          </template>
          <template v-slot:saleNum="props">
            <a-input
              :maxLength="20"
              v-model="props.value"
              :disabled="disabledShip(props)"
              placeholder="请输入"
              @input="(e) => saleNumInput(e, props)"
            />
          </template>
          <template v-slot:basicUnit="props">
            <a-select
              placeholder="请选择"
              showSearch
              :filter-option="filterOption"
              v-model="props.value"
              style="width: 100%"
              @select="(v) => selectUnit(v, props)"
              :disabled="disabledShip(props)"
            >
              <a-select-option v-for="(option, oi) in unitList(props)" :key="oi" :value="option.id">{{
                option.unit
              }}</a-select-option>
            </a-select>
          </template>
          <template v-slot:goodsId="props">
            <a-input
              :disabled="disabledShip(props)"
              placeholder="请选择"
              :read-only="true"
              @click="showSelect(props)"
              :value="goodsNameText(props)"
              :class="goodsNameText(props) ? 'has-value' : ''"
            >
              <a-icon slot="suffix" type="down" style="color: #cdcdcd; font-size: 12px" class="down-icon" />
              <a-icon
                slot="suffix"
                type="close-circle"
                theme="filled"
                class="close-icon"
                @click="getSelectValue(false, '', [], props.rowId)"
              />
            </a-input>
          </template>
        </j-editable-table>
      </a-card>
      <div style="margin-top: 12px" v-if="examineType == '0'">
        <Examine @submitProcess="submitProcess" :type="examineType" id="ERP_SALE_CONTRACT" ref="examine" />
        <div style="height: 50px"></div>
      </div>
    </div>
    <div class="footer-submit form-footer">
      <a-button v-if="!isEdit" :loading="loadingDraft" @click="submitDraft" style="margin-right: 10px"> 暂存 </a-button>
      <a-button type="primary" :loading="loadingSubmit" @click="submitProcess"> 提交 </a-button>
    </div>
    <goodsTableSelect ref="goodsTableSelect" @getSelectValue="getSelectValue" :key="selectIndex"> </goodsTableSelect>
    <goodsTableSelect ref="goodsTableSelectMulti" @getSelectValue="getSelectMultiValue" :key="selectMultiIndex">
    </goodsTableSelect>
  </jke-modal>
</template>
<script>
import crumbs from '@/components/crumbs.vue'
import FileUpload from '@/components/fileActions/FileUpload.vue'
import Examine from '@/components/examine'
import { API } from '@/api/requestFzs'
import moment from 'moment'
import JEditableTable from '@/components/jeecg/JEditableTable.vue'
import { validateTables, FormTypes, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
import { fourFloatNum, validateDuplicateValue, checkPrice } from '@/utils/util'
import goodsTableSelect from '@/components/goodsTableSelect'
import { pmDraftSave, pmDraftGet, pmDraftDel, customerQueryByIdIsExist, goodsQueryByIdIsExist } from '@/api/erpApi'
import PubImport from '@/components/pubBtn/PubImport.vue'
export default {
  data() {
    return {
      jkeForm: {
        title: '新建订单',
        visible: false,
        fullscreen: true,
        switchFullscreen: true,
      },
      validateDuplicateValue,
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      attachment: '',
      submitApi: API.erpSaleContractAdd,
      isEdit: false,
      loadingSubmit: false,
      customSelectList: [],
      goodsTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '物品编号 | 物品名称',
            width: '40%',
            key: 'goodsId',
            type: FormTypes.slot,
            placeholder: '请选择',
            slotName: 'goodsId',
            options: [],
            isrequired: true,
            allowSearch: true,
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '规格',
            width: '15%',
            key: 'spec',
            slotName: 'spec',
            defaultValue: '',
          },
          {
            title: '单位',
            width: '15%',
            key: 'unitId',
            // type: FormTypes.slot,
            // placeholder: '请输入${title}',
            slotName: 'basicUnit',
            // isrequired: true,
            defaultValue: '',
            // validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          {
            title: '基本单位',
            key: 'basicUnit',
            type: FormTypes.hidden,
            placeholder: '请输入${title}',
          },
          {
            title: '单位',
            key: 'unit',
            type: FormTypes.hidden,
            placeholder: '请输入${title}',
          },
          {
            title: '单位下拉',
            key: 'unitList',
            type: FormTypes.hidden,
            placeholder: '请输入${title}',
          },
          {
            title: '商品名称',
            key: 'goodsName',
            type: FormTypes.hidden,
            placeholder: '请输入${title}',
          },
          {
            title: '商品编号',
            key: 'goodsCode',
            type: FormTypes.hidden,
            placeholder: '请输入${title}',
          },
          {
            title: '商品规格',
            key: 'spec',
            type: FormTypes.hidden,
            placeholder: '请输入${title}',
          },
          {
            title: '数量',
            width: '20%',
            key: 'saleNum',
            type: FormTypes.slot,
            slotName: 'saleNum',
            isrequired: true,
            placeholder: '请输入${title}',
            defaultValue: '',
            validateRules: [
              { required: true, message: '${title}不能为空' },
              {
                pattern: /[1-9]+[0-9]*/,
                message: '${title}不能为空且必须大于0',
              },
            ],
          },
          // {
          //   title: '操作',
          //   width: '5%',
          //   key: 'action',
          //   type: FormTypes.slot,
          //   placeholder: '选择${title}',
          //   slotName: 'action',
          //   defaultValue: '',
          // },
        ],
      },
      queryId: '', // 校验编号唯一ID
      signUser: '',
      examineType: '0',
      allGoods: [],
      goodsProps: {},
      selectIndex: 0,
      selectMultiIndex: 0.1, // 商品多选组件key
      selectdGoodsIds: '', // 商品多选组件-选中值
      selectedGoodsNames: '', // 商品多选组件-选中值的名称
      selectColumns: [
        {
          title: '物品编号',
          width: 180,
          ellipsis: true,
          dataIndex: 'goodsCode',
          searchKey: 'goodsCode',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsCode',
          },
        },
        {
          title: '物品名称',
          width: 180,
          ellipsis: true,
          dataIndex: 'goodsName',
          searchKey: 'goodsName',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'goodsName',
          },
        },
        {
          title: '规格',
          width: 100,
          ellipsis: true,
          dataIndex: 'spec',
          searchKey: 'spec',
          scopedSlots: {
            filterDropdown: 'searchInput',
            filterIcon: 'searchIcon',
            customRender: 'spec',
          },
        },
        {
          title: '物品类型',
          width: 100,
          ellipsis: true,
          dataIndex: 'typeText',
          searchKey: 'type',
          type: 'select',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'typeText',
          },
        },
        {
          title: '物品分类',
          width: 100,
          ellipsis: true,
          dataIndex: 'categoryText',
          searchKey: 'category',
          type: 'tree',
          scopedSlots: {
            filterDropdown: 'selectDropdown',
            filterIcon: 'selectIcon',
            customRender: 'categoryText',
          },
        },
      ],
      filterForm: {},
      startValue: null,
      endValue: null,
      loadingDraft: false,
    }
  },
  components: {
    FileUpload,
    crumbs,
    JEditableTable,
    Examine,
    goodsTableSelect,
    PubImport,
  },
  methods: {
    disabledShip(p) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [p.rowId] }).values[0]
      let { hasShipping } = tableValue
      return hasShipping == 'true' ? true : false
    },
    // 限制开始日期
    disabledStartDate(startValue) {
      const endValue = this.endValue
      if (!startValue || !endValue) {
        return false
      }
      return startValue.valueOf() > endValue.valueOf()
    },
    // 限制结束日期
    disabledEndDate(endValue) {
      const startValue = this.startValue
      if (!endValue || !startValue) {
        return false
      }
      return startValue.valueOf() >= endValue.valueOf()
    },
    // 重置
    searchResetGoods() {
      this.filterForm = {}
      this.$refs.goodsTableSelect.searchReset()
    },
    // 筛选
    searchGoods() {
      this.$refs.goodsTableSelect.searchQuery(this.filterForm)
    },
    // 点击选择商品下拉框，弹出选择组件
    showSelect(p) {
      this.goodsProps = p
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [this.goodsProps.rowId] })
        .values[0]
      let par = {
        list: '/wms/goods/getAllGoodsBaseInfo',
        visible: true, //弹窗开启
        title: '商品', //标题名称
        multi: false, //是否多选
        columns: this.selectColumns, //表格配置
        value: tableValue.goodsId || '', //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: tableValue.goodsName || '', //回显的中文，如：'张三'
        textKey: 'goodsName', //回显的中文key
      }
      this.$refs.goodsTableSelect.getInit(par)
    },
    // 点击新增商品按钮，弹出多选组件
    selectMulti() {
      let par = {
        list: '/wms/goods/getAllGoodsBaseInfo',
        visible: true, //弹窗开启
        title: '商品', //标题名称
        multi: 'checkbox', //是否多选
        columns: this.selectColumns, //表格配置
        value: this.selectdGoodsIds || '', //需要回显的数据，如：id:'12323213,321312312,321312312'
        valueKey: 'id', //需要拿到数据的key，如：id，userId等
        text: this.selectedGoodsNames || '', //回显的中文，如：'张三'
        textKey: 'goodsName', //回显的中文key
      }
      this.$refs.goodsTableSelectMulti.getInit(par)
    },
    // 多选-选择商品回调
    async getSelectMultiValue(id, text, item) {
      console.log(id, text, item)
      var { values } = this.$refs.goodsTable.getValuesSync({ validate: false })
      let newArr = []
      let tips = ''
      /* 当前选择商品是否已存在列表中↓ */
      values.forEach((val) => {
        item.forEach((son) => {
          if (val.goodsId == son.id) {
            tips += `${son.goodsName},`
            son.delete = true
          }
        })
      })
      /* 若已存在列表中，则删除商品，不参与新增↓ */
      for (let i = 0; i < item.length; i++) {
        const good = item[i]
        if (!good.delete) {
          newArr.push({
            goodsId: good.id,
            goodsName: good.goodsName,
            goodsCode: good.goodsCode,
            spec: good.spec,
          })
        }
      }
      if (newArr.length > 0) {
        for (let j = 0; j < newArr.length; j++) {
          const son = newArr[j]
          const res = await API.findUnitListByGoodsIdSync({ goodsId: son.goodsId })
          let unitObj = res.result.find((u) => u.unitType == 'basic_unit')
          let info = {
            basicUnit: 'basic_unit',
            unit: unitObj.unit || '',
            unitId: unitObj.id,
            unitList: JSON.stringify(res.result),
          }
          newArr[j] = {
            ...son,
            ...info,
          }
        }
        this.goodsTable.dataSource = values.concat(newArr)
        this.selectedGoodsNames = ''
        this.selectdGoodsIds = ''
        this.selectMultiIndex += 1
        if (tips != '') {
          this.$antdMessage.warning(`商品：${tips}已存在，请直接修改数据`)
        }
      } else {
        this.selectedGoodsNames = ''
        this.selectdGoodsIds = ''
        this.selectMultiIndex += 1
        if (tips != '') {
          this.$antdMessage.warning(`商品：${tips}已存在，请直接修改数据`)
        }
      }
      console.log(this.goodsTable.dataSource, 'source')
    },
    // 选择商品回调
    getSelectValue(id, text, item, rowId) {
      console.log(id, text, item, rowId)
      this.selectIndex += 1 //重置组件去除表格默认勾选数据，让自己赋值的数据回显（重要！！！）
      if (!id) {
        this.$refs.goodsTable.setValues([
          {
            rowKey: rowId, // 行的id
            values: {
              // 在这里 values 中的 goodsId 是你 columns 中配置的 key
              goodsId: '',
              goodsName: '',
              goodsCode: '',
              spec: '',
              basicUnit: '',
              unit: '',
              unitList: '',
              unitId: '',
            },
          },
        ])
        return
      }
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false }).values
      for (let i = 0; i < tableValue.length; i++) {
        const item = tableValue[i]
        if (item.goodsId == id) {
          this.$refs.goodsTable.removeRows(this.goodsProps.rowId)
          this.$antdMessage.warning('该商品已存在，请直接修改数据')
          return
        }
      }
      this.$refs.goodsTable.setValues([
        {
          rowKey: this.goodsProps.rowId, // 行的id
          values: {
            // 在这里 values 中的 goodsId 是你 columns 中配置的 key
            goodsId: id,
            goodsName: text,
            goodsCode: item[0].goodsCode,
            spec: item[0].spec,
          },
        },
      ])
      this.setGoodsInfo(id, this.goodsProps.rowId)
      console.log(id, text, item, this.goodsProps.rowId, '列表选择的数据')
    },
    // 根据选择的商品带出其他商品信息并填充
    setGoodsInfo(value, rowId) {
      API.findUnitListByGoodsId({ goodsId: value }).then((res) => {
        var unitObj = res.result.find((u) => u.unitType == 'basic_unit')
        this.$refs.goodsTable.setValues([
          {
            rowKey: rowId, // 行的id
            values: {
              // 在这里 values 中的 specifications 是你 columns 中配置的 key
              basicUnit: 'basic_unit',
              unit: unitObj.unit || '',
              unitId: unitObj.id,
              unitList: JSON.stringify(res.result),
            },
          },
        ])
      })
      // this.$refs.goodsTable.getValuesSync({ validate: true, rowIds: [this.goodsProps.rowId] })
    },
    // 商品选择框回显值
    goodsNameText(p) {
      var item = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [p.rowId] }).values[0]
      // console.log('itemssssss:', p.rowId)
      return `${item.goodsCode ? item.goodsCode + ' | ' : ''}${item.goodsName ? item.goodsName : ''}`
    },
    selectUnit(v, p) {
      let list = this.unitList(p)
      let unitObj = list.find((item) => item.id == v)
      this.$refs.goodsTable.setValues([
        {
          rowKey: p.rowId, // 行的id
          values: {
            // 在这里 values 中的 specifications 是你 columns 中配置的 key
            basicUnit: unitObj.unitType,
            unit: unitObj.unit,
            unitId: v,
          },
        },
      ])
      this.$refs.goodsTable.getValuesSync({ validate: true, rowIds: [p.rowId] })
    },
    unitList(p) {
      var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false, rowIds: [p.rowId] }).values[0]
      // console.log(JSON.parse(tableValue.unitList),'tableValue.unitListtableValue.unitList');
      if (tableValue.unitList) {
        return JSON.parse(tableValue.unitList)
      }
      var list = []
      for (let i = 0; i < this.allGoods.length; i++) {
        const item = this.allGoods[i]
        if (item.goodsId == tableValue.goodsId) {
          list = item.unitList
        }
      }
      return list
    },
    /* 金额校验大于0 */
    validateToPrice(rule, value, callback) {
      if (/[1-9]+[0-9]*/.test(value)) {
        callback()
      } else {
        callback('金额必须大于0')
      }
    },
    /* 自动生成 */
    genEntityCode() {
      API.genEntityCode({ entityCode: 'ERP_SALE_CONTRACT' }).then((res) => {
        if (res.code == 200) {
          this.form.setFieldsValue({
            contractCode: res.result,
          })
        } else {
          this.$antdMessage.error(res.message)
        }
      })
    },
    /* 选定签订人 */
    userFilter(v, row) {
      if (row.length > 0) {
        this.signUser = v
        this.userId = row[0].id
        this.form.setFieldsValue({
          signUserCode: v,
        })
      } else {
        this.signUser = ''
        this.userId = ''
        this.form.setFieldsValue({
          signUserCode: '',
        })
      }
    },
    inputPrice(e) {
      this.form.setFieldsValue({
        amount: checkPrice(e.target.value),
      })
    },
    // 下拉搜索
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleDeleteGood(p) {
      this.$refs.goodsTable.removeRows(p.rowId)
    },
    saleNumInput(e, p) {
      this.$refs.goodsTable.setValues([
        {
          rowKey: p.rowId, // 行的id
          values: {
            // 在这里 values 中的 specifications 是你 columns 中配置的 key
            saleNum: fourFloatNum(e.target.value),
          },
        },
      ])
      this.$refs.goodsTable.getValuesSync({ validate: true, rowIds: [p.rowId] })
    },
    valueChange(type) {
      if (type.column.key == 'saleNum') {
        this.$refs.goodsTable.setValues([
          {
            rowKey: type.row.id, // 行的id
            values: {
              // 在这里 values 中的 specifications 是你 columns 中配置的 key
              saleNum: fourFloatNum(type.value),
            },
          },
        ])
      }
      return
      if (type.column.key == 'goodsId') {
        if (!type.value) {
          this.$refs.goodsTable.setValues([
            {
              rowKey: type.row.id, // 行的id
              values: {
                // 在这里 values 中的 specifications 是你 columns 中配置的 key
                basicUnit: '',
                unit: '',
                unitId: '',
              },
            },
          ])
          return
        }
        var goodSelectItem = this.goodsTable.columns[0].options.find((item) => item.value === type.value)
        var tableValue = this.$refs.goodsTable.getValuesSync({ validate: false }).values
        var newArr = []
        tableValue.forEach((v) => {
          newArr.push(v.goodsId)
        })
        var newArrLen = [...new Set(newArr)].length
        var oldArrLen = tableValue.length
        if (newArrLen < oldArrLen) {
          this.$refs.goodsTable.removeRows(type.row.id)
          this.$antdMessage.warning('该商品已存在，请直接修改数据')
          return
        }
        var hasGood = false
        API.findUnitListByGoodsId({ goodsId: type.value }).then((res) => {
          for (let i = 0; i < this.allGoods.length; i++) {
            const item = this.allGoods[i]
            if (item.goodsId == type.value) {
              hasGood = true
            }
          }
          if (!hasGood) {
            this.allGoods.push({
              goodsId: type.value,
              unitList: res.result,
            })
            var unitObj = res.result.find((u) => u.unitType == 'basic_unit')
            this.$refs.goodsTable.setValues([
              {
                rowKey: type.row.id, // 行的id
                values: {
                  // 在这里 values 中的 specifications 是你 columns 中配置的 key
                  basicUnit: 'basic_unit',
                  unit: unitObj.unit || '',
                  unitId: unitObj.id,
                },
              },
            ])
          }
        })
      }
    },
    /* 下拉数据 */
    getGoods() {
      /* 获取商品下拉数据 */
      API.getAllGoodsBaseInfo({ pageSize: 999, pageNo: 1 }).then((res) => {
        if (res.code == 200) {
          if (res.result.records) {
            this.goodsTable.columns[0].options = []
            res.result.records.forEach((item) => {
              // item.title = item.goodsName
              item.title = `${item.goodsCode ? item.goodsCode + ' | ' : ''}${
                item.goodsName ? item.goodsName + ' | ' : ''
              }${item.spec ? item.spec : ''}`
              item.text = `${item.goodsCode ? item.goodsCode + ' | ' : ''}${
                item.goodsName ? item.goodsName + ' | ' : ''
              }${item.spec ? item.spec : ''}`
              item.value = item.id
              this.goodsTable.columns[0].options.push(item)
            })
          }
          // this.goodsTable.columns[0].options = res.result.records || []
        } else {
          this.$antdMessage.error(res.message)
        }
      })
      /* 客户下拉 */
      API.erpCustomerList({ pageSize: 999, pageNo: 1, effectStatus: 'effective' }).then((res) => {
        if (res.code == 200) {
          console.log('res.result', res.result)
          this.customSelectList = res.result.records
        }
      })
    },
    /* 选择物料后查询带出物料信息 */
    selectChange(v) {
      if (!v) {
        this.form.setFieldsValue({
          spec: '-',
          basicUnitText: '-',
          typeText: '-',
          categoryText: '-',
          goodsId: '',
        })
        return
      }
    },
    selectCustom(v) {
      console.log(v)
    },
    /* 面包屑返回 */
    goBack() {
      this.jkeForm.visible = false
    },
    /* 获取编辑详情 */
    initForm(id) {
      Object.assign(this.$data, this.$options.data.call(this))
      this.jkeForm.visible = true
      this.getGoods()
      if (id) {
        this.queryId = id
        this.examineType = '1'
        this.jkeForm.title = '编辑订单'
        this.submitApi = API.erpSaleContractEdit
        this.isEdit = true
        this.goodsTable.columns.push({
          title: '是否申请发货了',
          key: 'hasShipping',
          type: FormTypes.hidden,
        })
        API.erpSaleContractQueryById({ id: id }).then((res) => {
          if (res.code == 200) {
            let editForm = res.result
            this.signUser = editForm.signUserId
            editForm.signUserCode = editForm.signUserId
            this.$nextTick(() => {
              this.attachment = res.result.attachment
              this.userId = res.result.userId
              this.signUser = res.result.signUser
              this.form.setFieldsValue(editForm)
            })
            this.attachment = res.result.attachment
            let newGoodsList = res.result.erpSaleContractEditVoList
            for (let i = 0; i < newGoodsList.length; i++) {
              const good = newGoodsList[i]
              let unit = good.unitList.find((u) => u.id == good.unitId)
              if (!unit) {
                good.unitId = undefined
              }
              good.basicUnit = good.unitType
              good.unitList = JSON.stringify(good.unitList)
            }
            this.allGoods = newGoodsList
            this.goodsTable.dataSource = newGoodsList
            console.log(newGoodsList)
          }
        })
      } else {
        this.jkeForm.title = '新建订单'
        // 如果是新建，先查询是否有暂存表单，有就回显暂存表单
        pmDraftGet({
          entityType: 'SALES_CONTRACT_FORM',
        }).then((res) => {
          if (res.result && res.result.isDraft) {
            this.checkFormInfoAsync(res.result.editable, res.result.form, res.result.attachment)
          }
        })
      }
    },
    /* 表单中部分数据受外部影响，可能被删除或已被使用，回显暂存数据时先校验，被影响的数据直接清除或清0 */
    async checkFormInfoAsync(list, form, attachment) {
      this.attachment = attachment
      let that = this
      /* 校验物品是否存在 ---begin--- */
      let goodsList = list
      for (let i = 0; i < goodsList.length; i++) {
        const item = goodsList[i]
        const goodsIsExist = await goodsQueryByIdIsExist({ id: item.goodsId })
        const unitRes = await API.findUnitListByGoodsIdSync({ goodsId: item.goodsId })
        if (!goodsIsExist) {
          goodsList.splice(i, 1)
        } else {
          let goodInfo = goodsIsExist.result
          item.goodsName = goodInfo.goodsName
          item.goodsCode = goodInfo.goodsCode
          item.spec = goodInfo.spec
          item.unitList = JSON.stringify(unitRes.result)
        }
      }
      that.goodsTable.dataSource = goodsList
      /* 校验物品是否存在 ---end--- */

      /* 校验客户是否存在 ---begin--- */
      const customerIsExist = await customerQueryByIdIsExist({ id: form.customerId })
      if (form.customerId && !customerIsExist) {
        form.customerId = undefined
      }
      this.form.setFieldsValue(form)
      /* 校验客户是否存在 ---end--- */
    },
    /* 获取附件 */
    getFileList(v) {
      this.attachment = v
      console.log('上传的附件id：', v)
    },
    // 提交（必须使用名为submitProcess方法进行提交）
    submitProcess(e) {
      if (this.isEdit) {
        this.handleSubmit()
      } else {
        if (e.nodeDtos) {
          // 获取到数据后写表单提交的方法
          this.handleSubmit(e)
        } else {
          // 调用子组件的方法获取数据
          this.$refs.examine.confirm()
        }
      }
    },
    handleSubmit(processDataVo) {
      let errArr = []
      let parameters = {}
      let formData = {}
      let { error, values } = this.$refs.goodsTable.getValuesSync({ validate: true })
      if (error === 0) {
      } else {
        errArr.push(false)
      }
      this.form.validateFields((err, formValues) => {
        if (!err) {
          parameters = { ...formValues, attachment: this.attachment }
          if (this.isEdit) {
            parameters.id = this.queryId
          } else {
            parameters.processDataVo = processDataVo
          }
          if (errArr.length == 0) {
            let erpSaleContractItemSaveDtoList = values.map((g, i) => {
              return {
                goodsId: g.goodsId,
                id: g.id,
                saleNum: g.saleNum,
                unitType: g.basicUnit,
                unit: g.unit,
                unitId: g.unitId,
              }
            })
            parameters.erpSaleContractItemSaveDtoList = erpSaleContractItemSaveDtoList
            parameters.signUserId = this.userId
            parameters.contractStartDate = parameters.contractStartDate
              ? moment(parameters.contractStartDate).format('YYYY-MM-DD')
              : ''
            parameters.contractEndDate = parameters.contractEndDate
              ? moment(parameters.contractEndDate).format('YYYY-MM-DD')
              : ''
            parameters.signDate = parameters.signDate ? moment(parameters.signDate).format('YYYY-MM-DD') : ''
            // parameters.promiseDate = parameters.promiseDate ? moment(parameters.promiseDate).format('YYYY-MM-DD') : ''
            console.log(parameters)
            this.loadingSubmit = true
            this.submitApi(parameters).then((res) => {
              this.loadingSubmit = false
              if (res.code == 200) {
                let subMsg = this.isEdit ? '合同编辑成功！' : '合同新建成功！'
                pmDraftDel({ entityType: 'SALES_CONTRACT_FORM' }).then((res) => {})
                this.$antdMessage.success(subMsg)
                this.$emit('refresh')
                this.goBack()
              } else {
                this.$antdMessage.error(res.message)
              }
            })
          }
        } else {
        }
      })
    },
    submitDraft() {
      // pmDraftSave
      let { values } = this.$refs.goodsTable.getValuesSync({ validate: false })
      this.form.validateFields((err, formValues) => {
        let draft = {
          form: formValues,
          editable: values,
          attachment: this.attachment,
          userId: this.userId,
          signUser: this.signUser,
          isDraft: true,
        }
        this.loadingDraft = true
        pmDraftSave({
          draft,
          entityType: 'SALES_CONTRACT_FORM',
        }).then((res) => {
          if (res.code == 200) {
            this.$antdMessage.success(res.message)
            this.goBack()
          } else {
            this.$antdMessage.error(res.message)
          }
          this.loadingDraft = false
        })
      })
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
/deep/.ant-form-vertical {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .ant-form-item {
    width: 30%;
  }
}
.form-body {
  height: calc(100vh - 100px);
  overflow-y: scroll;
}
.form-footer {
  position: absolute;
  bottom: 0;
  right: 0;
  padding-left: 100px;
  z-index: 2;
}
.code-btn {
  position: absolute;
  right: 0;
  top: -34.5px;
}
</style>
